import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { useParams, useNavigate } from 'react-router-dom';
import { User, Mail, Calendar, Shield, BarChart4, Clock, ChevronLeft } from 'lucide-react';
import axios from 'axios';

const UserDetailsContainer = styled.div`
  padding: 24px;
  background-color: #f8fafc;
  min-height: 100vh;
`;

const Header = styled.div`
  display: flex;
  align-items: center;
  margin-bottom: 24px;
`;

const BackButton = styled.button`
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  color: #64748b;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:hover {
    background-color: #f1f5f9;
    color: #334155;
  }
`;

const Title = styled.h1`
  font-size: 1.5rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
`;

const ProfileCard = styled.div`
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  display: flex;
  gap: 24px;
`;

const Avatar = styled.div`
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #6366f1, #a855f7);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 2.5rem;
  flex-shrink: 0;
`;

const ProfileInfo = styled.div`
  flex: 1;
`;

const UserName = styled.h2`
  font-size: 1.75rem;
  font-weight: 700;
  color: #1e293b;
  margin: 0 0 8px 0;
`;

const UserEmail = styled.p`
  color: #64748b;
  margin: 0 0 16px 0;
  display: flex;
  align-items: center;
  gap: 8px;
`;

const BadgeContainer = styled.div`
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
`;

const StatusBadge = styled.span`
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 0.75rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  background-color: ${props => props.active ? '#dcfce7' : '#fee2e2'};
  color: ${props => props.active ? '#15803d' : '#b91c1c'};
`;

const RoleBadge = styled.span`
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 0.75rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  
  ${props => {
    switch(props.role) {
      case 'admin':
        return `background-color: #dbeafe;
                color: #1e40af;
               `;
      case 'vip':
        return `background-color: #fef3c7;
                color: #92400e;
               `;
      default:
        return `background-color: #e5e7eb;
                color: #374151;
               `;
    }
  }}
`;

const DetailGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
`;

const DetailItem = styled.div`
  display: flex;
  flex-direction: column;
`;

const DetailLabel = styled.span`
  font-size: 0.75rem;
  color: #94a3b8;
  margin-bottom: 4px;
`;

const DetailValue = styled.span`
  font-size: 0.875rem;
  color: #334155;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
`;

const AnalysisCard = styled.div`
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
`;

const SectionTitle = styled.h3`
  font-size: 1.25rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 16px 0;
`;

const AnalysisTable = styled.table`
  width: 100%;
  border-collapse: collapse;
`;

const AnalysisHeader = styled.th`
  text-align: left;
  padding: 12px 16px;
  border-bottom: 1px solid #e2e8f0;
  color: #64748b;
  font-size: 0.875rem;
  font-weight: 600;
`;

const AnalysisRow = styled.tr`
  &:hover {
    background-color: #f8fafc;
  }
`;

const AnalysisCell = styled.td`
  padding: 12px 16px;
  border-bottom: 1px solid #e2e8f0;
  color: #334155;
  font-size: 0.875rem;
`;

const LoadingContainer = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  color: #64748b;
  font-size: 1.1rem;
`;

const ErrorContainer = styled.div`
  background: #fee2e2;
  color: #b91c1c;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 8px;
`;

const NoDataContainer = styled.div`
  text-align: center;
  padding: 40px 20px;
  color: #64748b;
`;

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

const UserDetails = () => {
  const { userId } = useParams();
  const navigate = useNavigate();
  const [user, setUser] = useState(null);
  const [analyses, setAnalyses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchUserDetails = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 在实际项目中，这里应该调用真实的API接口
        // const response = await axios.get(`/admin/users/${userId}`);
        // setUser(response.data);
        
        // 模拟数据加载延迟
        await new Promise(resolve => setTimeout(resolve, 800));
        
        // 模拟用户数据
        const mockUser = {
          id: parseInt(userId),
          username: `user${userId}`,
          email: `user${userId}@example.com`,
          role: parseInt(userId) === 3 ? 'admin' : parseInt(userId) % 3 === 0 ? 'vip' : 'regular',
          active: parseInt(userId) !== 6 && parseInt(userId) !== 10,
          createdAt: new Date(Date.now() - (parseInt(userId) * 3) * 24 * 60 * 60 * 1000).toISOString(),
          lastLogin: new Date(Date.now() - (parseInt(userId) % 7) * 24 * 60 * 60 * 1000).toISOString(),
          analysesCount: 10 + parseInt(userId) * 3,
          vipExpiration: parseInt(userId) % 3 === 0 ? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString() : null,
          avatar: null
        };
        
        setUser(mockUser);
        
        // 模拟分析记录数据
        const mockAnalyses = Array.from({ length: 5 }, (_, index) => ({
          id: index + 1,
          type: ['面相分析', '手相分析', '八字测算', '塔罗牌解读', '风水评估'][index % 5],
          date: new Date(Date.now() - index * 24 * 60 * 60 * 1000).toISOString(),
          duration: 2 + Math.floor(Math.random() * 10), // 分钟
          result: '分析已完成',
          paymentAmount: index % 3 === 0 ? 99 : 0
        }));
        
        setAnalyses(mockAnalyses);
      } catch (err) {
        console.error('获取用户详情失败:', err);
        setError('获取用户详情失败，请稍后再试');
      } finally {
        setLoading(false);
      }
    };

    fetchUserDetails();
  }, [userId]);

  const handleBack = () => {
    navigate(-1);
  };

  if (loading) {
    return (
      <UserDetailsContainer>
        <LoadingContainer>正在加载用户详情...</LoadingContainer>
      </UserDetailsContainer>
    );
  }

  if (error) {
    return (
      <UserDetailsContainer>
        <ErrorContainer>{error}</ErrorContainer>
        <BackButton onClick={handleBack}>
          <ChevronLeft size={18} /> 返回用户列表
        </BackButton>
      </UserDetailsContainer>
    );
  }

  if (!user) {
    return (
      <UserDetailsContainer>
        <ErrorContainer>用户不存在</ErrorContainer>
        <BackButton onClick={handleBack}>
          <ChevronLeft size={18} /> 返回用户列表
        </BackButton>
      </UserDetailsContainer>
    );
  }

  return (
    <UserDetailsContainer>
      <Header>
        <BackButton onClick={handleBack}>
          <ChevronLeft size={18} />
        </BackButton>
        <Title>用户详情</Title>
      </Header>

      <ProfileCard>
        <Avatar>
          {user.username.charAt(0).toUpperCase()}
        </Avatar>
        <ProfileInfo>
          <UserName>{user.username}</UserName>
          <UserEmail>
            <Mail size={16} /> {user.email}
          </UserEmail>
          <BadgeContainer>
            <StatusBadge active={user.active}>
              {user.active ? '活跃' : '禁用'}
            </StatusBadge>
            <RoleBadge role={user.role}>
              {user.role === 'admin' ? '管理员' : user.role === 'vip' ? 'VIP用户' : '普通用户'}
            </RoleBadge>
          </BadgeContainer>
          <DetailGrid>
            <DetailItem>
              <DetailLabel>注册时间</DetailLabel>
              <DetailValue>
                <Calendar size={16} /> {formatDate(user.createdAt)}
              </DetailValue>
            </DetailItem>
            <DetailItem>
              <DetailLabel>最后登录</DetailLabel>
              <DetailValue>
                <Clock size={16} /> {formatDate(user.lastLogin)}
              </DetailValue>
            </DetailItem>
            <DetailItem>
              <DetailLabel>分析次数</DetailLabel>
              <DetailValue>
                <BarChart4 size={16} /> {user.analysesCount} 次
              </DetailValue>
            </DetailItem>
            {user.vipExpiration && (
              <DetailItem>
                <DetailLabel>VIP到期</DetailLabel>
                <DetailValue>
                  <Shield size={16} /> {formatDate(user.vipExpiration)}
                </DetailValue>
              </DetailItem>
            )}
          </DetailGrid>
        </ProfileInfo>
      </ProfileCard>

      <AnalysisCard>
        <SectionTitle>最近分析记录</SectionTitle>
        {analyses.length > 0 ? (
          <AnalysisTable>
            <thead>
              <tr>
                <AnalysisHeader>分析类型</AnalysisHeader>
                <AnalysisHeader>分析时间</AnalysisHeader>
                <AnalysisHeader>耗时</AnalysisHeader>
                <AnalysisHeader>状态</AnalysisHeader>
                <AnalysisHeader>金额</AnalysisHeader>
              </tr>
            </thead>
            <tbody>
              {analyses.map(analysis => (
                <AnalysisRow key={analysis.id}>
                  <AnalysisCell>{analysis.type}</AnalysisCell>
                  <AnalysisCell>{formatDate(analysis.date)}</AnalysisCell>
                  <AnalysisCell>{analysis.duration} 分钟</AnalysisCell>
                  <AnalysisCell>{analysis.result}</AnalysisCell>
                  <AnalysisCell>{analysis.paymentAmount > 0 ? `¥${analysis.paymentAmount}` : '免费'}</AnalysisCell>
                </AnalysisRow>
              ))}
            </tbody>
          </AnalysisTable>
        ) : (
          <NoDataContainer>暂无分析记录</NoDataContainer>
        )}
      </AnalysisCard>
    </UserDetailsContainer>
  );
};

export default UserDetails;